package com.bayi.storage.network;

import com.bayi.storage.network.entity.ApiException;
import com.bayi.storage.network.entity.BaseDataBody;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/5/9.
 * <p>
 * 站在顶峰 看世界
 * 落到谷底 思人生
 */

public class DefaultTransformer<T> implements Observable.Transformer<T, T> {

    private final int maxRetries;

    public DefaultTransformer(int maxRetries) {
        this.maxRetries = maxRetries;
    }

    @Override
    public Observable<T> call(Observable<T> tObservable) {
        // 通用错误处理，判断code
        return tObservable
                .retryWhen(new RetryWithDelay(maxRetries, 3000))
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(t -> {
                    if (((BaseDataBody) t).code == RetrofitHelper.CODE) {
                        new ApiException(((BaseDataBody) t).code, ((BaseDataBody) t).msg);
                    }
                    return t;
                });
    }

    public static <T> DefaultTransformer<T> create(int maxRetries) {
        return new DefaultTransformer<>(maxRetries);
    }
}
